/**
 * @file sport.c
 * @brief 运动检测功能相关
 */

 /*********************
 *      INCLUDE
 *********************/
//导入库
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//导入自定义头文件
#include "sport.h"
#include "lv_demo_music_main.h"
#include "lv_demo_music_list.h"
#include "lrc_parser.h"
#include "utf-8_to_gbk.h"

/**********************
 *  STATIC PROTOTYPES
 **********************/
static void popup_item_event_cb(lv_event_t * e);
static void popup_close_event_cb(lv_event_t * e);
static void popup_bg_event_cb(lv_event_t * e);
static void custom_info_confirm_cb(lv_event_t * e);
static void import_popup_item_event_cb(lv_event_t * e);
static void import_popup_close_event_cb(lv_event_t * e);
static void import_popup_close_event_cb_to_setting(lv_event_t * e);
static int find_option_index(const char* options, const char* target);

/**********************
 *      DEFINES
 **********************/
#define MOTION_POPUP_COOLDOWN_MINUTES 15    // 弹窗冷却时间（分钟）
#define MILLISECONDS_PER_MINUTE 60000       // 每分钟的毫秒数


/**********************
 *  STATIC VARIABLES
 **********************/
static lv_obj_t * settings_popup_bg = NULL;
static lv_obj_t * import_popup_bg = NULL;
// 添加运动歌单弹窗相关变量
lv_obj_t * sport_popup_bg = NULL;
bool sport_playlist_mode = false;  // 运动歌单模式标志
uint32_t sport_track_ids[MAX_TRACKS] = {0};  // 运动歌曲ID数组
uint32_t sport_track_count = 0;    // 运动歌曲数量

// 添加弹窗冷却时间控制
static uint32_t popup_cooldown_until = 0;  // 弹窗冷却结束时间（毫秒时间戳）

extern void lv_demo_music_switch_to_normal_playlist(void);

/**********************
 *   GLOBAL FUNCTIONS
 **********************/

 /**
 * @brief 切换到运动歌单
 */
void lv_demo_music_switch_to_sport_playlist(void)
{
    sport_playlist_mode = true;

    // 收集所有运动标签的歌曲
    sport_track_count = 0;
    for (int i = 0; i < track_count; i++) {
        if (condition_list[i] && strcmp(condition_list[i], "运动") == 0) {
            sport_track_ids[sport_track_count] = i;
            sport_track_count++;
        }
    }

    printf("[SPORT PLAYLIST] 切换到运动歌单，找到 %d 首运动歌曲\n", sport_track_count);

    if (sport_track_count > 0) {
        // 随机选择一首运动歌曲播放
        uint32_t random_index = rand() % sport_track_count;
        uint32_t track_id = sport_track_ids[random_index];
        _lv_demo_music_play(track_id);
    } else {
        printf("[SPORT PLAYLIST] 警告：没有找到运动标签的歌曲\n");
        sport_playlist_mode = false;
    }
}

/**
 * @brief 切换到普通歌单
 */
void lv_demo_music_switch_to_normal_playlist(void)
{
    sport_playlist_mode = false;
    printf("[SPORT PLAYLIST] 切换到普通歌单\n");
}

/**
 * @brief 检查是否在运动歌单模式
 * @return true:运动歌单模式, false:普通模式
 */
bool lv_demo_music_is_sport_playlist_mode(void)
{
    return sport_playlist_mode;
}

/**
 * @brief 在运动歌单模式下随机选择下一首运动歌曲
 */
void lv_demo_music_play_next_sport_track(void)
{
    if (!sport_playlist_mode || sport_track_count == 0) {
        return;
    }

    // 随机选择下一首运动歌曲
    uint32_t random_index = rand() % sport_track_count;
    uint32_t track_id = sport_track_ids[random_index];

    // 避免重复播放同一首歌
    if (sport_track_count > 1) {
        while (track_id == track_id) { // 如果随机到同一首，重新选择
            random_index = rand() % sport_track_count;
            track_id = sport_track_ids[random_index];
        }
    }

    printf("[SPORT PLAYLIST] 随机播放下一首运动歌曲: ID=%d\n", track_id);
    _lv_demo_music_play(track_id);
}

/**
 * @brief 显示运动歌单选择弹窗
 */
void _lv_demo_music_show_sport_playlist_popup(void)
{
    // 如果已有弹窗，先关闭
    if(sport_popup_bg) {
        lv_obj_del(sport_popup_bg);
        sport_popup_bg = NULL;
    }

    // 创建弹窗背景（半透明遮罩）
    sport_popup_bg = lv_obj_create(lv_scr_act());
    lv_obj_set_size(sport_popup_bg, LV_HOR_RES, LV_VER_RES);
    lv_obj_set_style_bg_color(sport_popup_bg, lv_color_black(), 0);
    lv_obj_set_style_bg_opa(sport_popup_bg, LV_OPA_50, 0);
    lv_obj_set_style_radius(sport_popup_bg, 0, 0);
    lv_obj_clear_flag(sport_popup_bg, LV_OBJ_FLAG_SCROLLABLE);
    lv_obj_add_flag(sport_popup_bg, LV_OBJ_FLAG_CLICKABLE);

    // 创建弹窗容器
    lv_obj_t * popup = lv_obj_create(sport_popup_bg);

    // 设置弹窗样式
#if LV_DEMO_MUSIC_LARGE
    lv_obj_set_size(popup, 300, 200);
#else
    lv_obj_set_size(popup, 250, 180);
#endif
    lv_obj_align(popup, LV_ALIGN_CENTER, 0, 0);
    lv_obj_set_style_bg_color(popup, lv_color_white(), 0);
    lv_obj_set_style_radius(popup, 12, 0);
    lv_obj_set_flex_flow(popup, LV_FLEX_FLOW_COLUMN);
    lv_obj_set_flex_align(popup, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
    lv_obj_set_style_pad_all(popup, 20, 0);

    // 标题
    lv_obj_t * title = lv_label_create(popup);
    lv_label_set_text(title, "运动歌单");
    lv_obj_set_style_text_font(title, font_large, 0);
    lv_obj_set_style_text_color(title, lv_color_hex(0x504d6d), 0);
    lv_obj_set_style_pad_bottom(title, 10, 0);

    // 提示信息
    lv_obj_t * hint = lv_label_create(popup);
    lv_label_set_text(hint, "检测到您在运动\n是否切换到运动歌单？");
    lv_obj_set_style_text_font(hint, font_small, 0);
    lv_obj_set_style_text_color(hint, lv_color_hex(0x504d6d), 0);
    lv_obj_set_style_text_align(hint, LV_TEXT_ALIGN_CENTER, 0);
    lv_obj_set_style_pad_bottom(hint, 20, 0);

    // 按钮容器
    lv_obj_t * btn_cont = lv_obj_create(popup);
    lv_obj_remove_style_all(btn_cont);
    lv_obj_set_size(btn_cont, lv_pct(100), LV_SIZE_CONTENT);
    lv_obj_set_flex_flow(btn_cont, LV_FLEX_FLOW_ROW);
    lv_obj_set_flex_align(btn_cont, LV_FLEX_ALIGN_SPACE_EVENLY, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);

    // 是按钮
    lv_obj_t * yes_btn = lv_btn_create(btn_cont);
    lv_obj_set_size(yes_btn, 80, 40);
    lv_obj_t * yes_label = lv_label_create(yes_btn);
    lv_label_set_text(yes_label, "是");
    lv_obj_set_style_text_font(yes_label, font_small, 0);
    lv_obj_center(yes_label);
    lv_obj_add_event_cb(yes_btn, sport_popup_yes_cb, LV_EVENT_CLICKED, NULL);

    // 否按钮
    lv_obj_t * no_btn = lv_btn_create(btn_cont);
    lv_obj_set_size(no_btn, 80, 40);
    lv_obj_t * no_label = lv_label_create(no_btn);
    lv_label_set_text(no_label, "否");
    lv_obj_set_style_text_font(no_label, font_small, 0);
    lv_obj_center(no_label);
    lv_obj_add_event_cb(no_btn, sport_popup_no_cb, LV_EVENT_CLICKED, NULL);
}

//弹窗触发状态的调用
void sport_popup_yes_cb(lv_event_t * e)
{
    if(sport_popup_bg) {
        lv_obj_del(sport_popup_bg);
        sport_popup_bg = NULL;
    }

    printf("[SPORT PLAYLIST] 用户选择了：是，切换到运动歌单\n");

    // 重置弹窗触发状态，允许重新检测
    extern void reset_motion_popup_trigger(void);
    reset_motion_popup_trigger();

    // 设置15分钟冷却时间
    set_motion_popup_cooldown(MOTION_POPUP_COOLDOWN_MINUTES);

    // 切换到运动歌单
    extern void lv_demo_music_switch_to_sport_playlist(void);
    lv_demo_music_switch_to_sport_playlist();
}


static void sport_popup_no_cb(lv_event_t * e)
{
    if(sport_popup_bg) {
        lv_obj_del(sport_popup_bg);
        sport_popup_bg = NULL;
    }

    printf("[SPORT PLAYLIST] 用户选择了：否，保持当前歌单\n");

    // 重置弹窗触发状态，允许重新检测
    extern void reset_motion_popup_trigger(void);
    reset_motion_popup_trigger();

    // 设置15分钟冷却时间
    set_motion_popup_cooldown(MOTION_POPUP_COOLDOWN_MINUTES);

    // 确保切换到普通歌单
    lv_demo_music_switch_to_normal_playlist();
}

/**
 * @brief 运动弹窗触发函数
 * 当连续检测到15次运动时调用
 */
void trigger_motion_popup(void)
{
    printf("[POPUP] 触发运动检测弹窗\n");
    // 调用LVGL弹窗函数
    _lv_demo_music_show_sport_playlist_popup();
}

//-----------------------------------<弹窗冷却相关>---------------------------------------------------------------
/**
 * @brief 检查是否在弹窗冷却时间内
 * @return true:在冷却时间内, false:可以弹出弹窗
 */
bool is_motion_popup_in_cooldown(void)
{
    if (popup_cooldown_until == 0) {
        return false; // 未设置冷却时间
    }

    uint32_t current_time = GetTickCount();
    return (current_time < popup_cooldown_until);
}

/**
 * @brief 设置弹窗冷却时间
 * @param minutes 冷却时间（分钟）
 */
void set_motion_popup_cooldown(uint32_t minutes)
{
    uint32_t current_time = GetTickCount();
    popup_cooldown_until = current_time + (minutes * MILLISECONDS_PER_MINUTE);

    printf("[POPUP COOLDOWN] 设置弹窗冷却时间: %d分钟, 冷却结束时间: %lu\n",
           minutes, popup_cooldown_until);
}

/**
 * @brief 清除弹窗冷却时间
 */
void clear_motion_popup_cooldown(void)
{
    popup_cooldown_until = 0;
    printf("[POPUP COOLDOWN] 清除弹窗冷却时间\n");
}

/**
 * @brief 获取剩余冷却时间（秒）
 * @return 剩余冷却时间（秒），0表示不在冷却中
 */
uint32_t get_remaining_cooldown_seconds(void)
{
    if (popup_cooldown_until == 0) {
        return 0;
    }

    uint32_t current_time = GetTickCount();
    if (current_time >= popup_cooldown_until) {
        popup_cooldown_until = 0; // 冷却时间已过，清除
        return 0;
    }

    return (popup_cooldown_until - current_time) / 1000;
}
